<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useUserStore } from '@/store/modules/user-store'
import { searchApi } from '@/api/search/search-api'
let map = null

const initMap = async () => {
  window._AMapSecurityConfig = {
    securityJsCode: '98ed597fdab99b3580ded9e3d1f19d4e'
  }
  const AMap = await AMapLoader.load({
    key: 'e3ad28f39ebf5c7d5fb1d7153fb2f3b4', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Icon', 'AMap.Size', 'AMap.Marker', 'AMap.LngLat', 'AMap.Pixel']
  })
  // 获取地图中心点
  const { getCenterLocal } = useUserStore()
  const center = getCenterLocal.map(Number)

  // 初始化地图
  map = new AMap.Map('container', {
    rotateEnable: false,
    pitchEnable: false,
    zoom: 15,
    pitch: 45,
    // rotation: 45,
    viewMode: '2D', //开启3D视图,默认为关闭
    zooms: [2, 20],
    center
  })

  // 创建网点自定义标记内容
  const createStoreMarkerContent = (name) => {
    return `
        <div style="display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: red;"></div>
    `
  }

  // 创建网点坐标点
  const { data } = await searchApi.storeList({ fields: 'id,store_name,lon,lat', filter: {}, op: {} })

  const storeMarkers = data
    .filter((item) => item.lon && item.lat)
    .map((item) => {
      const storeMarkerContent = createStoreMarkerContent(item.store_name)
      return new AMap.Marker({
        position: new AMap.LngLat(Number(item.lon), Number(item.lat)),
        title: item.store_name,
        content: storeMarkerContent,
        offset: new AMap.Pixel(0, -40)
      })
    })

  map?.add(storeMarkers)
}

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  map?.destroy()
})
</script>
<template>
  <div id="container"></div>
</template>
<style scoped>
#container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100vh;
}
</style>
